﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Clipping.Infrastructure.Models;
using System.Threading.Tasks;
using System.Net;
using System.IO;

namespace Settings
{
    /// <summary>
    /// Interaction logic for InfoFileUpdate.xaml
    /// </summary>
    public partial class InfoFileUpdate : Window
    {
        SysSettings setting;
        private string appDir = AppDomain.CurrentDomain.BaseDirectory;
        private Log4cb.Log4cbHelper logHelper;



        private WebClient wc_ClientInfo;
        private WebClient wc_MediaInfo;
        private WebClient wc_UserInfo;
        private bool ClientInfoUpdated;
        private bool UserInfoUpdated;
        private bool MediaInfoUpdated;

        public InfoFileUpdate()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(InfoFileUpdate_Loaded);
        }

        public InfoFileUpdate(SysSettings setting, Log4cb.Log4cbHelper logHelper)
            : this()
        {
            this.setting = setting;
            this.logHelper = logHelper;
            if (this.logHelper == null)
                this.logHelper = new Log4cb.Log4cbHelper("Setting");
        }

        void InfoFileUpdate_Loaded(object sender, RoutedEventArgs e)
        {
            if (setting == null)
                this.Close();
            bool updateAny = false;
            if (!string.IsNullOrEmpty(setting.ClientInfoUrl) && Uri.IsWellFormedUriString(setting.ClientInfoUrl, UriKind.Absolute))
            {
                updateAny = true;
                updateClientInfo();
            }
            else
            {
                this.ClientInfoUpdated = true;
            }
            if (!string.IsNullOrEmpty(setting.UserInfoUrl) && Uri.IsWellFormedUriString(setting.UserInfoUrl, UriKind.Absolute))
            {
                updateAny = true;
                updateUserInfo();
            }
            else
            {
                this.UserInfoUpdated = true;
            }
            if (!string.IsNullOrEmpty(setting.MediaInfoUrl) && Uri.IsWellFormedUriString(setting.MediaInfoUrl, UriKind.Absolute))
            {
                updateAny = true;
                updateMediaInfo();
            }
            else 
            {
                this.MediaInfoUpdated = true;
            }
            if (updateAny == false)
                this.Close();
        }

       
      

        private void updateClientInfo()
        {
            wc_ClientInfo = new WebClient();
            wc_ClientInfo.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_ClientInfo_DownloadProgressChanged);
            wc_ClientInfo.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_ClientInfo_DownloadStringCompleted);
            wc_ClientInfo.Encoding = Encoding.UTF8;
            Uri clienturl = new Uri(setting.ClientInfoUrl);
            wc_ClientInfo.DownloadStringAsync(clienturl);

        }
        void wc_ClientInfo_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            this.Dispatcher.Invoke((Action)(() => { this.pb_ClientInfo.Value = e.ProgressPercentage; }));
        }
        void wc_ClientInfo_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    string xmlstr = e.Result;
                    ensureDataFolderCreated();
                    File.WriteAllText(System.IO.Path.Combine(appDir, "Data", "ClientInfo.xml"), xmlstr, Encoding.UTF8);
                    this.ClientInfoUpdated = true;
                    CheckAllDone();
                }
                else
                {
                    this.logHelper.LogErrMsg(e.Error, "更新客户分类信息失败");
                }
            }
            catch (Exception ex)
            {
                this.logHelper.LogErrMsg(ex, "更新客户分类信息失败");
                MessageBox.Show(string.Format("更新客户分类信息失败：{0}{1}", Environment.NewLine, ex.Message), "失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                wc_ClientInfo.Dispose();
 
            }
        }



        private void updateUserInfo()
        {
            wc_UserInfo = new WebClient();
            wc_UserInfo.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_UserInfo_DownloadProgressChanged);
            wc_UserInfo.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_UserInfo_DownloadStringCompleted);
            wc_UserInfo.Encoding = Encoding.UTF8;
            Uri userInfoUrl = new Uri(setting.UserInfoUrl );
            wc_UserInfo.DownloadStringAsync(userInfoUrl);
        }
        void wc_UserInfo_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    string xmlstr = e.Result;
                    ensureDataFolderCreated();
                    File.WriteAllText(System.IO.Path.Combine(appDir, "Data", "UserInfo.xml"), xmlstr, Encoding.UTF8);
                    this.UserInfoUpdated = true;
                    CheckAllDone();
                }
                else
                {
                    this.logHelper.LogErrMsg(e.Error, "更新用户信息失败");
                }
            }
            catch (Exception ex)
            {
                this.logHelper.LogErrMsg(ex, "更新用户信息失败");
                MessageBox.Show(string.Format("更新用户信息失败：{0}{1}", Environment.NewLine, ex.Message), "失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                wc_UserInfo.Dispose();
            }
        }
        void wc_UserInfo_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            this.Dispatcher.Invoke((Action)(() => { this.pb_UserInfo.Value = e.ProgressPercentage; }));
        }

        private void updateMediaInfo()
        {
            wc_MediaInfo = new WebClient();
            wc_MediaInfo.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_MediaInfo_DownloadProgressChanged);
            wc_MediaInfo.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_MediaInfo_DownloadStringCompleted);
            wc_MediaInfo.Encoding = Encoding.UTF8;
            Uri mediaInfoUrl = new Uri(setting.MediaInfoUrl);
            wc_MediaInfo.DownloadStringAsync(mediaInfoUrl);
        }

        void wc_MediaInfo_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    string xmlstr = e.Result;
                    ensureDataFolderCreated();
                    File.WriteAllText(System.IO.Path.Combine(appDir, "Data", "MediaList.xml"), xmlstr, Encoding.UTF8);
                    this.MediaInfoUpdated = true;
                    CheckAllDone();
                }
                else
                {
                    this.logHelper.LogErrMsg(e.Error, "更新媒体信息失败");
                }
            }
            catch (Exception ex)
            {
                this.logHelper.LogErrMsg(ex, "更新媒体信息失败");
                MessageBox.Show(string.Format("更新媒体信息失败：{0}{1}", Environment.NewLine, ex.Message), "失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                wc_UserInfo.Dispose();

            }
        }

        void wc_MediaInfo_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            this.Dispatcher.Invoke((Action)(() => { this.pb_MediaInfo.Value = e.ProgressPercentage; }));
        }


        private void ensureDataFolderCreated()
        {
            var dir = System.IO.Path.Combine(appDir, "Data");
            if (!System.IO.Directory.Exists(dir))
                System.IO.Directory.CreateDirectory(dir);
        }


        private void CheckAllDone()
        {
            if (this.MediaInfoUpdated && this.UserInfoUpdated && this.ClientInfoUpdated)
                this.Close();
        }


        private void btn_Cancel_Click(object sender, RoutedEventArgs e)
        {
            if (wc_ClientInfo != null)
            {
                try
                {
                    wc_ClientInfo.CancelAsync();
                    wc_ClientInfo.Dispose();
                }
                catch { }
            }
            if (wc_UserInfo != null)
            {
                try
                {
                    wc_UserInfo.CancelAsync();
                    wc_UserInfo.Dispose();
                }
                catch { }
            }
            if (wc_MediaInfo != null)
            {
                try
                {
                    wc_MediaInfo.CancelAsync();
                    wc_MediaInfo.Dispose();
                }
                catch { }
            }
            this.Close();
        }
    }
}
